package org.example.controller;

import jakarta.annotation.Resource;
import org.example.pojo.Voice;
import org.example.service.VoiceService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 文本转语音调用控制器
 *
 * @author rjs
 */
@RestController
public class TTSController {

    /**
     * 语音服务
     */
    @Resource
    private VoiceService voiceService;

    /**
     * 调用文本转语音服务
     *
     * @param params 请求参数
     * @return 处理结果
     */
    @PostMapping("/convert")
    public String convert(@RequestBody Map<String, String> params) {

        // 获取文本参数
        String text = params.get("text");

        // 构建请求数据
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("text", text);

        // 发送请求调用文本转语音服务
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, null);
        ResponseEntity<byte[]> response = restTemplate.exchange(
                "http://localhost:5000/convert",
                HttpMethod.POST,
                request,
                byte[].class);

        // 检查响应结果
        if (response.getStatusCode().is2xxSuccessful()) {
            byte[] audio = response.getBody();

            // 保存转换后的语音
            Voice voice = new Voice();
            voice.setVoice(audio);
            voiceService.save(voice);

            return "音频成功保存";

        } else {
            return "无法将文本转换为语音";
        }

    }

}

